<?php

/**
 * 
 * 删除文件
 * 该程序并不能真正删除文件本身，而是删除服务器上记录的其文件信息
 */

include './init_db.php';


$username = defaultGetData('username', '');
$password = defaultGetData('password', '');
$objectId = defaultGetData('objectId', '');


if (!$username || !$password || !$objectId) {
    die(json_encode(array(
        'code' => 999,
        'msg' => '参数缺失'
    )));
}


$result = mysqli_query($conn, "SELECT * FROM `cloudDisk_user` WHERE (`username` = '$username' OR `email` = '$username') AND `password` = '$password' LIMIT 1");
if (!mysqli_num_rows($result)) {
    die(json_encode(array(
        'code' => 1000,
        'msg' => '账号或密码错误'
    )));
}

// 获取用户空间用量
$used_capacity = 0;
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $used_capacity = (int)$row['used_capacity'];
}

// 判断文件objectId是否存在
$result2 = mysqli_query($conn, "SELECT * FROM `cloudDisk_file` WHERE `objectId` = '$objectId' LIMIT 1");
if (!mysqli_num_rows($result2)) {
    die(json_encode(array(
        'code' => 992,
        'msg' => '没有找到该文件'
    )));
}


// 获取被删除的文件的大小
$size;
while ($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
    $size = (int)$row['size'];
}


// 删除文件记录
$result = mysqli_query($conn, "DELETE FROM `cloudDisk_file` WHERE `objectId` = '$objectId' LIMIT 1");

if (!$result) {
    die(json_encode(array(
        'code' => 995,
        'msg' => '操作失败：' . mysqli_error($conn)
    )));
}




// 释放用户空间
$used_capacity -= (int)($size / 1024);
if ($used_capacity < 0) {
    $used_capacity = 0;
}
$r = mysqli_query($conn, "UPDATE `cloudDisk_user` SET `used_capacity` = '$used_capacity' WHERE `username` = '$username' LIMIT 1");
if (!$r) {
    die(json_encode(array(
        'code' => 995,
        'msg' => '操作失败：' . mysqli_error($conn)
    )));
}

echo json_encode(array(
    'code' => 200,
    'msg' => '文件删除成功'
));
